<?php

namespace app\common\model\xilumarket;

use app\common\model\User;
use think\Db;
use think\Log;
use think\Model;
use function fast\array_except;
use function fast\array_get;


class TopicUser extends Model
{
    // 表名
    protected $name = 'xilumarket_topic_user';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $append = [
        'createtime_text', 'is_admin_text'
    ];

    public function getCreatetimeTextAttr($value,$data){
        if(isset($data['createtime'])){
            return xilumarket_time_cha(time(),$data['createtime']);
        }
        return '';
    }

    public function topic(){
        return $this->belongsTo(Topic::class,'topic_id','id')->setEagerlyType(0);
    }
    public function user(){
        return $this->belongsTo(User::class,'user_id','id')->setEagerlyType(0);
    }

    public static function getCount($where){
        return self::where($where)->count(1);
    }

    public function getIsAdminTextAttr($value, $data) {
        if(!isset($data['is_admin'])){
            return null;
        }
        return [11=>'吧主', 10=>'管理员', '00' => '用户', '0' => '用户'][$data['is_admin']];
    }

    /**
     * 话题用户
     */
    public static function getUsers($topicId,$pagesize){
        $lists = self::with(['user'=>function($query){
            $query->withField(['id','nickname','username','avatar']);
        }])
            ->where('topic_id',$topicId)
            ->order('updatetime','desc')
            ->limit($pagesize)
            ->select();
        return $lists;
    }

    /**
     * @param int $userId
     * @param int $recordId
     * @param $type
     * @return bool|string true是已收藏状态, false是未收藏状态
     */
    public static function toggleJoin($userId, $recordId) {
        Db::startTrans();
        try {
            $model = static::where('topic_id', $recordId)
                ->where('user_id', $userId)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new self([
                    'user_id' => $userId,
                    'topic_id' => $recordId
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    return $model->getError();
                }
                $result = true;
            }
            $count = self::where('topic_id', $recordId)->count();
            Topic::where('id', $recordId)->update(['join_user_count' => $count]);
            Db::commit();
            return $result;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            Db::rollback();
            return false;
        }
    }

    /**
     * 用户是否加入
     * @param $userId
     * @param $recordId
     * @return bool
     */
    public static function isJoinTopic($recordId,$userId) {
        if(!$userId || !$recordId)
            return false;
        return static::where('topic_id',$recordId)
                ->where('user_id',$userId)
                ->count() > 0;
    }

    /**
     * 关联禁言用户
     *
     * @return void
     */
    public function ban() {
        return $this->hasOne(TopicBanUser::class, 'topic_user_id', 'id');
    }

    /**
     * 检查是否是贴吧用户
     */
    public function checkUser($uid) {
        return $this->where(['topic_id' => $this->topic_id, 'user_id' => $uid])->find();
    }

    /**
     * 检查是否是吧主
     *
     * @return void
     */
    public function checkMaster() {
        return $this->is_admin == 11;
    }

    /**
     * 检查是否是管理员
     *
     * @return void
     */
    public function checkAdmin() {
        return $this->is_admin > 01;
    }
}
